package com.xiaoyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoyi.entity.ResultBody;
import com.xiaoyi.entity.SysMenu;
import com.xiaoyi.service.SysMenuService;
import com.xiaoyi.service.SysRoleMenuService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author 小易
 * @version 1.0
 * @description TODO 系统菜单
 * @date 2022/12/16 14:22
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {

    @Resource
    private SysMenuService menuService;

    @Resource
    private SysRoleMenuService roleMenuService;

    /**
     * @description 添加或修改
     * @param menu 角色信息
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 14:06
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:menu:add') || hasAuthority('system:menu:edit')")
    public ResultBody save(@RequestBody SysMenu menu){
        if (menu.getId() == null || menu.getId() == -1){
            menu.setCreateTime(new Date());
            menuService.save(menu);
        }else {
            menu.setUpdateTime(new Date());
            menuService.updateById(menu);
        }
        return ResultBody.success();
    }

    /**
     * @description 删除
     * @param menuId 菜单id
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 14:18
     */
    @GetMapping("/delete/{menuId}")
    @PreAuthorize("hasAuthority('system:menu:delete')")
    public ResultBody delete(@PathVariable("menuId") Long menuId){
        // 如果是父目录，则不可以删除
        int parentCount = menuService.count(new QueryWrapper<SysMenu>().eq("parent_id", menuId));
        if (parentCount > 0) return ResultBody.error("请先删除子目录！");
        menuService.removeById(menuId);
        return ResultBody.success();
    }

    /**
     * @description 查询菜单树
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 14:27
     */
    @GetMapping("/treeList")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public ResultBody treeList(){
        List<SysMenu> menuList = menuService.list(new QueryWrapper<SysMenu>().orderByAsc("order_num"));
        List<SysMenu> treeMenuList = menuService.buildTreeMenu(menuList);
        return ResultBody.success(treeMenuList);
    }

    /**
     * @description 根据id查询
     * @param id 菜单id
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 14:07
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public ResultBody findById(@PathVariable("id") Integer id){
        SysMenu menu = menuService.getById(id);
        return ResultBody.success(menu);
    }

}
